package com.agileai.pm.module.test.handler;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.FileUploadHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.pm.cxmodule.WcmGeneralGroup8ContentManage;
import com.agileai.pm.module.test.service.TestProjectShortcomManage;

public class PictureUploadHandler
        extends FileUploadHandler {
	
    private static final String ResourceGroupId = "CF35D1E6-102E-428A-B39C-0072D491D5B1";

    public PictureUploadHandler() {
        super();
    }
    public ViewRenderer prepareDisplay(DataParam param) {
        String grpId = ResourceGroupId;
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        DataParam queryParam = new DataParam("GRP_ID", grpId);
        DataRow row = resourseManage.queryTreeRecord(queryParam);
        String resTypeDesc = row.stringValue("GRP_RES_TYPE_DESC");
        String resTypeExts = row.stringValue("GRP_RES_TYPE_EXTS");
        String resSizeLimit = row.stringValue("GRP_RES_SIZE_LIMIT");
        
        this.setAttribute("BIZ_ID", param.get("BIZ_ID"));
        this.setAttribute("GRP_ID", grpId);
        this.setAttribute("GRP_RES_TYPE_DESC", resTypeDesc);
        this.setAttribute("GRP_RES_TYPE_EXTS", resTypeExts);
        this.setAttribute("GRP_RES_SIZE_LIMIT", resSizeLimit);

        return new LocalRenderer(getPage());
    }

    @SuppressWarnings("rawtypes")
    @PageAction
    public ViewRenderer uploadFile(DataParam param) {
        String responseText = FAIL;
        String location =null;
        String bizId =null;
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
            fileFileUpload.setHeaderEncoding("utf-8");
            List fileList = null;
            fileList = fileFileUpload.parseRequest(request);
            Iterator it = fileList.iterator();
            String name = "";
            String fileFullPath = null;
            File filePath = this.buildResourseSavePath(ResourceGroupId);
            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("BIZ_ID")) {
                        bizId = item.getString();
                        resourceParam.put("BIZ_ID", bizId);
                    }
                    continue;
                }
                name = item.getName();
                
                WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
				DataParam queryParam = new DataParam("GRP_ID",ResourceGroupId);
				DataRow row = resourseManage.queryTreeRecord(queryParam);
				String resTypeExts = row.stringValue("GRP_RES_TYPE_EXTS");
				
                resourceParam.put("GRP_ID", ResourceGroupId);
                resourceParam.put("RES_NAME", name);
                String suffix = name.substring(name.lastIndexOf("."));
                this.checkSuffix(suffix, resTypeExts);
                
                String enName = KeyGenerator.instance().genShortKey() + suffix;
                location = resourceRelativePath + "/" + enName;
                resourceParam.put("RES_LOCATION", location);
                fileFullPath = filePath.getAbsolutePath() + File.separator + enName;
                setAttribute("location",location);
                long resourceSize = item.getSize();
                resourceParam.put("RES_SIZE", String.valueOf(resourceSize));
                resourceParam.put("RES_SUFFIX", suffix);
                resourceParam.put("RES_SHAREABLE", "Y");
                File tempFile = new File(fileFullPath);
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                item.write(tempFile);
                this.insertResourceRecord();
            }
          
            responseText = SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxRenderer(responseText);
    }

	private void insertResourceRecord() {
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        resourseManage.createtContentRecord("WcmGeneralResource", resourceParam);

        String resId = resourceParam.get("RES_ID");
        String bizId = resourceParam.get("BIZ_ID");
      //利用自己的service 构造一个插入图片与商品的关联数据
        DataParam param=new DataParam();
        param.put("TDIR_ID",KeyGenerator.instance().genKey());
        param.put("PD_ID",resId);
        param.put("TPD_ID",bizId);
        TestProjectShortcomManage testservice=this.getService();
        testservice.inserDefectImgRel(param);
    }
 
	//在这里得到自己的service
	protected TestProjectShortcomManage getService() {
	    return (TestProjectShortcomManage) this.lookupService(TestProjectShortcomManage.class);
	}
}
